package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.sys.domain.SysRole;
import cn.harry.modular.sys.enums.StatusEnums;
import cn.harry.modular.sys.service.SysRoleService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ClassName: SysRoleController Description:
 *
 * @author honghh Date 2019/10/17 10:00 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/role")
@Tag(name = "Sys-role => 角色管理")
public class SysRoleController {

    private final SysRoleService sysRoleService;

    @Operation(summary = "list 分页列表")
    @Parameters({
            @Parameter(name = "current", description = "当前页", required = true, example = "1"),
            @Parameter(name = "size", description = "每页显示条数", required = true, example = "10")
    })
    @PreAuthorize("@ss.hasPermission('system:role:list')")
    @GetMapping(value = "/list")
    public R<IPage<SysRole>> list(@Parameter(hidden = true) Page<SysRole> page, SysRole sysRole) {
        return R.success(sysRoleService.page(page, Wrappers.lambdaQuery(sysRole)));
    }

    @Operation(summary = "listAll 获取所有角色列表")
    @GetMapping(value = "/listAll")
    public R<List<SysRole>> listAll() {
        List<SysRole> roles = sysRoleService.list(Wrappers.<SysRole>lambdaQuery()
                .eq(SysRole::getStatus, StatusEnums.ENABLE.getKey()));
        return R.success(roles);
    }

    @Operation(summary = "{id} 根据角色ID获取详细信息")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    @GetMapping("/{id}")
    public R<SysRole> info(@PathVariable("id") Long id) {
        SysRole role = sysRoleService.getById(id);
        return R.success(role);
    }

    @Operation(summary = "创建指定角色信息")
    @PreAuthorize("@ss.hasPermission('system:role:add')")
    @SysLog(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Integer> create(@RequestBody SysRole sysRole) {
        return sysRoleService.create(sysRole) ? R.success() : R.failed();
    }

    @Operation(summary = "修改指定角色信息")
    @PreAuthorize("@ss.hasPermission('system:role:edit')")
    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Integer> update(@RequestBody SysRole sysRole) {
        return sysRoleService.update(sysRole.getId(), sysRole) ? R.success() : R.failed();
    }

    @Operation(summary = "dataScope 修改数据权限")
    @PreAuthorize("@ss.hasPermission('system:role:edit')")
    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/dataScope")
    public R<Integer> dataScope(@RequestBody SysRole sysRole) {
        return sysRoleService.dataScope(sysRole) ? R.success() : R.failed();
    }

    @Operation(summary = "remove 删除角色")
    @PreAuthorize("@ss.hasPermission('system:role:remove')")
    @SysLog(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> delete(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return sysRoleService.deleteByIds(ids) ? R.success() : R.failed();
    }

    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @Operation(summary = "changeStatus 状态修改")
    @PutMapping("/changeStatus")
    public R<Integer> changeStatus(@RequestBody SysRole role) {
        return R.success(sysRoleService.updateRoleStatus(role));
    }

    @Operation(summary = "export 按条件导出（不分页）")
    @PreAuthorize("@ss.hasPermission('system:role:export')")
    @SysLog(title = "角色管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(HttpServletResponse response, SysRole role) {
        List<SysRole> list = sysRoleService.getExportList(role);
        try {
            EasyExcel.write(response.getOutputStream(), SysRole.class).sheet("角色管理")
                    .doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("角色管理,导出失败 error:{}", e.getMessage());
        }
        return R.failed();

    }

}
